import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:orginone/components/ListSearchWidget/ListSearchWidget.dart';
import 'package:orginone/components/TabContainerWidget/TabContainerWidget.dart';
import 'package:orginone/components/TabContainerWidget/types.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/controller/index.dart';
import 'package:orginone/dart/core/public/consts.dart';
import 'package:orginone/dart/core/public/entity.dart';
import 'package:orginone/dart/core/public/enums.dart';
import 'package:orginone/dart/core/target/base/target.dart';
import 'package:orginone/dart/core/target/outTeam/istorage.dart';
import 'package:orginone/dart/core/thing/directory.dart';
import 'package:orginone/dart/core/work/index.dart';
import 'package:orginone/dart/core/work/task.dart';
import 'package:orginone/main.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/utils/date_util.dart';
import '../../components/CommandWidget/index.dart';
import '../../components/XStatefulWidget/XStatefulWidget.dart';
import '../../dart/base/common/commands.dart';
import '../../utils/log/log_util.dart';

class WorkPage extends XStatefulWidget {
  late TabContainerModel? workModel;
  late dynamic datas;
  WorkPage({super.key, dynamic datas}) {
    workModel = null;
    this.datas = datas ?? RoutePages.getRouteParams(homeEnum: HomeEnum.work);
  }

  @override
  State<StatefulWidget> createState() => _WorkPageState();
}

class _WorkPageState extends State<WorkPage> {
  TabContainerModel? get workModel => widget.workModel;
  final ScrollController scrollController = ScrollController();
  set workModel(TabContainerModel? value) {
    widget.workModel = value;
  }

  dynamic get datas => widget.datas;
  set datas(dynamic datas) => widget.datas;
  RxList<IWorkTask> get todos => relationCtrl.work.todos;
  @override
  void initState() {
    super.initState();
    workModel = null;
    datas = RoutePages.getRouteParams(homeEnum: HomeEnum.store);
    todos.listen((values) {
      if (mounted) {
        setState(() {
          widget.workModel = null;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return _buildMainView();
  }

  _buildMainView() {
    // if (null == workModel) {
    //   load(context);
    // }
    return CommandWidget<TabContainerWidget>(
        type: 'work',
        cmd: 'refresh',
        builder: (context, args) {
          load(context);
          return TabContainerWidget(workModel!);
        });
  }

  TabContainerModel? load(BuildContext context) {
    return workModel = TabContainerModel(
        activeTabTitle: getActiveTabTitle() ?? "待办",
        title: RoutePages.getRouteTitle() ?? "数据",
        tabItems: [
          createTabItemsModel(context, title: "常用"),
          createTabItemsModel(context, title: "草稿"),
          createTabItemsModel(context, title: "任务"),
          createTabItemsModel(context, title: "待办"),
          createTabItemsModel(context, title: "已办"),
          createTabItemsModel(context, title: "抄送"),
          createTabItemsModel(context, title: "已发起"),
          createTabItemsModel(context, title: "已完结")
        ],
    );
  }

  /// 获得激活页签
  getActiveTabTitle() {
    return RoutePages.getRouteDefaultActiveTab()?.firstOrNull;
  }

  TabItemsModel createTabItemsModel(
      BuildContext context, {
        required String title,
      }) {
    return TabItemsModel(
        title: title, content: _buildTabItemWidget(context, title));
  }

  _buildTabItemWidget(BuildContext context, String title) {
    // List<IEntity> initCommons = [];
    return ListSearchWidget(
      // initDatas: initCommons,
      onInitLoad: ([String? searchText]) async {
        return await getFirstLevelDirectories(title, searchText ?? "" , true);
      },
      onLoad: ([String? searchText]) async {
        command.emitter('work', 'refresh');
        return getFirstLevelDirectories(title, searchText ?? "", false);
      },
      scrollController: scrollController,
      getAction: (dynamic data) {
        return Text(
          CustomDateUtil.getSessionTime(data.updateTime),
          style: XFonts.chatSMTimeTip,
          textAlign: TextAlign.right,
        );
      },
      onTap: (dynamic data, List children) {
        // XLogUtil.d('>>>>>>======点击了列表项 ${data.name} ${children.length}');
        if (data is IWorkTask) {
          RoutePages.jumpWorkInfo(context: context, work: data);
        } else if (data is IWork) {
          RoutePages.jumpNewWork(context: context, work: data);
        }
      },
    );
  }

  // 获得一级目录
  Future<List<IEntity>> getFirstLevelDirectories(String title, String searchText, bool reload) async {
    List<IEntity> dataCommons = [];
    if (title == "常用") {
      dataCommons = (await relationCtrl.loadCommonsOther(relationCtrl.user))
          .where((element) => element.typeName == '办事' && element.search(searchText))
          .toList();
    } else if (title == "草稿") {
      dataCommons = (await relationCtrl.work.loadContent(TaskType.draft, reload: reload)).where((element) => element.search(searchText)).toList();
    } else if (title == "待办") {
      dataCommons = relationCtrl.work.todos.where((element) => element.search(searchText)).toList();
    } else if (title == "已办") {
      dataCommons = (await relationCtrl.work.loadContent(TaskType.done, reload: reload)).where((element) => element.search(searchText)).toList();
    } else if (title == "抄送") {
      dataCommons = (await relationCtrl.work.loadContent(TaskType.altMe, reload: reload)).where((element) => element.search(searchText)).toList();
    } else if (title == "已发起") {
      dataCommons = (await relationCtrl.work.loadContent(TaskType.create, reload: reload)).where((element) => element.search(searchText)).toList();
    } else if (title == "已完结") {
      dataCommons = (await relationCtrl.work.loadContent(TaskType.completed, reload: reload)).where((element) => element.search(searchText)).toList();
    }
    return dataCommons;
  }

  // 加载存储列表
  List<IStorage> loadStorages(ITarget target) {
    TargetType? type = TargetType.getType(target.typeName);
    if (type == TargetType.person) {
      return relationCtrl.user?.storages ?? [];
    } else if (type == TargetType.company) {
      return relationCtrl.user?.findCompany(target.id)?.storages ?? [];
    }
    return [];
  }

  /// 加载存储列表
  List<Directory> loadStoragesDirectory(IStorage data) {
    List<Directory> datas = [];
    XDirectory tmpDir;
    int id = 0;
    if (null != relationCtrl.user) {
      DirectoryGroupType.getType(data.typeName)?.types.forEach((e) {
        tmpDir = XDirectory(
            id: id.toString(), directoryId: id.toString(), isDeleted: false);
        tmpDir.name = e.label;
        tmpDir.typeName = e.label;
        datas.add(Directory(tmpDir, relationCtrl.user!));
      });
    }
    return datas;
  }

  /// 加载数据标准
  List<Directory> loadDataStandards(Directory item) {
    List<Directory> datas = [];
    XDirectory tmpDir;
    int id = 0;
    if (null != relationCtrl.user) {
      DirectoryGroupType.getType(item.typeName)?.types.forEach((e) {
        tmpDir = XDirectory(
            id: id.toString(), directoryId: id.toString(), isDeleted: false);
        tmpDir.name = e.label;
        tmpDir.typeName = e.label;
        datas.add(Directory(tmpDir, relationCtrl.user!));
      });
    }
    return datas;
  }
}
